from collections import deque


def read_last_n_lines(file_path2, n):
    with open(file_path2, 'r', encoding='utf-8') as file:
        last_n_lines = deque(file, n)
        for line in reversed(last_n_lines):
            print(line.strip())


def read_last_n_lines2(file_path, n):
    with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:  # 使用 errors='ignore' 跳过无法解码的字符
        lines = []
        file.seek(0, 2)  # 将文件指针移动到末尾
        file_size = file.tell()
        pos = file_size - 1  # 初始化文件指针位置

        # 从文件末尾向前搜索换行符来读取行
        while len(lines) < n and pos >= 0:
            file.seek(pos)
            char = file.read(1)
            if char == '\n':
                lines.append(file.readline().strip())
            pos -= 1

        # 逆序输出最后的 n 行
        for line in reversed(lines):
            print(line)


if __name__ == '__main__':
    file_path_all = r'e:\ad.txt'  # 替换为你的文件路径
    read_last_n_lines2(file_path_all, 1)
    # print(abc)
